package com.sunday.haowushop.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.haowushop.R;
import com.sunday.haowushop.common.BaseApp;
import com.sunday.haowushop.entity.Member;
import com.sunday.haowushop.entity.OrderNums;
import com.sunday.haowushop.entity.Statistic;
import com.sunday.haowushop.http.ApiClient;
import com.sunday.haowushop.ui.WebViewActivity;
import com.sunday.haowushop.ui.mine.AddressListActivity;
import com.sunday.haowushop.ui.mine.MessageListActivity;
import com.sunday.haowushop.ui.mine.MyIntegralActivity;
import com.sunday.haowushop.ui.mine.TeacherShareActivity;
import com.sunday.haowushop.ui.mine.TotalProfitActivity;
import com.sunday.haowushop.ui.mine.baseinfo.ShopInfoActivity;
import com.sunday.haowushop.ui.mine.customer.CustomerListActivity;
import com.sunday.haowushop.ui.mine.customer.CustomerManageActivity;
import com.sunday.haowushop.ui.mine.customer.PerformanceActivity;
import com.sunday.haowushop.ui.mine.sales.SalesActivity;
import com.sunday.haowushop.ui.mine.share.ShareGiftActivity;
import com.sunday.haowushop.ui.mine.voucher.VoucherListActivity;
import com.sunday.haowushop.ui.order.OrderListActivity;
import com.sunday.haowushop.ui.order.RefundOrderListActivity;
import com.sunday.haowushop.ui.shop.ShopManageActivity;
import com.sunday.haowushop.widgets.ShareWindow;

import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.everything.android.ui.overscroll.OverScrollDecoratorHelper;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/5/3.
 */

public class ShopFragment extends BaseFragment {


    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.left_menu)
    ImageView leftMenu;
    @Bind(R.id.right_menu)
    ImageView rightMenu;
    @Bind(R.id.user_logo)
    CircleImageView userLogo;
    @Bind(R.id.layout1)
    RelativeLayout layout1;
    @Bind(R.id.shop_name)
    TextView shopName;
    @Bind(R.id.shop_number)
    TextView shopNumber;
    @Bind(R.id.layout2)
    LinearLayout layout2;
    @Bind(R.id.layout3)
    LinearLayout layout3;
    @Bind(R.id.header_layout)
    RelativeLayout headerLayout;
    @Bind(R.id.menu_order_1)
    TextView menuOrder1;
    @Bind(R.id.menu_order_2)
    TextView menuOrder2;
    @Bind(R.id.menu_order_3)
    TextView menuOrder3;
    @Bind(R.id.shop_menu1)
    TextView shopMenu1;
    @Bind(R.id.shop_menu2)
    TextView shopMenu2;
    @Bind(R.id.shop_menu3)
    TextView shopMenu3;
    @Bind(R.id.shop_menu4)
    TextView shopMenu4;
    @Bind(R.id.shop_menu5)
    TextView shopMenu5;
    @Bind(R.id.shop_menu6)
    TextView shopMenu6;
    @Bind(R.id.shop_menu7)
    TextView shopMenu7;
    @Bind(R.id.shop_menu8)
    TextView shopMenu8;
    @Bind(R.id.order_no)
    TextView orderNum;
    @Bind(R.id.sale_num)
    TextView saleNum;
    @Bind(R.id.profit_num)
    TextView profitNum;
    @Bind(R.id.fans_num)
    TextView fansNum;


    private long memberId;
    private Statistic statistic;
    private Member member;


    public static ShopFragment newInstance() {
        ShopFragment shopFragment = new ShopFragment();
        Bundle args = new Bundle();
        shopFragment.setArguments(args);
        return shopFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.layout_shop_fragment, container, false);
        ButterKnife.bind(this, rootView);
        ScrollView scrollView = (ScrollView) rootView.findViewById(R.id.scrollView);
        OverScrollDecoratorHelper.setUpOverScroll(scrollView);
        return rootView;

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        member = BaseApp.getInstance().getMember();
        memberId = member.getId();
        initView();
        getStatistics();
    }


    private void initView() {
        if (member == null) {
            return;
        }
        if (!TextUtils.isEmpty(member.getShopLogo())) {
            Glide.with(mContext)
                    .load(member.getShopLogo())
                    .error(R.mipmap.ic_default)
                    .into(userLogo);
        }
        shopName.setText(member.getShopName());
        shopNumber.setText("店铺邀请码：" + member.getInitCode());
    }

    public void getStatistics() {
        Call<ResultDO<Statistic>> call = ApiClient.getApiAdapter().getStatistic(BaseApp.getInstance().getMember().getId());
        call.enqueue(new Callback<ResultDO<Statistic>>() {
            @Override
            public void onResponse(Call<ResultDO<Statistic>> call, Response<ResultDO<Statistic>> response) {
                if (isFinish) {
                    return;
                }
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    statistic = response.body().getResult();
                    updateView();
                    getOrderNums();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Statistic>> call, Throwable t) {

            }
        });
    }

    public void getOrderNums() {
        Call<ResultDO<OrderNums>> call = ApiClient.getApiAdapter().getOrderCount(memberId, 2);
        call.enqueue(new Callback<ResultDO<OrderNums>>() {
            @Override
            public void onResponse(Call<ResultDO<OrderNums>> call, Response<ResultDO<OrderNums>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    updateOrderNums(response.body().getResult());
                }

            }

            @Override
            public void onFailure(Call<ResultDO<OrderNums>> call, Throwable t) {

            }
        });
    }


    private void updateView() {
        if (statistic == null) {
            return;
        }
        orderNum.setText(String.valueOf(statistic.getTodayOrder()));
        saleNum.setText(String.format("%s", statistic.getMonthSale().setScale(2, RoundingMode.HALF_UP)));
        profitNum.setText(String.format("%s", statistic.getMonthTotalScale().setScale(2, RoundingMode.HALF_UP)));
        fansNum.setText(String.valueOf(statistic.getMemberSize()));
    }

    Badge badge1, badge2, badge3;

    private void updateOrderNums(OrderNums orderNums) {
        if (orderNums.getWaitPay() >= 0) {
            if (badge1 == null) {
                badge1 = new QBadgeView(mContext).bindTarget(menuOrder1).setBadgeNumber(orderNums.getWaitPay());
                badge1.setShowShadow(false);
                badge1.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.colorPrimary), true);
                badge1.setGravityOffset(16, true);
                badge1.setBadgeTextSize(10, true);
            } else {
                badge1.setBadgeNumber(orderNums.getWaitPay());
            }
        }
        if (orderNums.getWaitSend() >= 0) {
            if (badge2 == null) {
                badge2 = new QBadgeView(mContext).bindTarget(menuOrder2).setBadgeNumber(orderNums.getWaitSend());
                badge2.setShowShadow(false);
                badge2.setGravityOffset(16, true);
                badge2.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.colorPrimary), true);
                badge2.setBadgeTextSize(10, true);
            } else {
                badge2.setBadgeNumber(orderNums.getWaitSend());
            }

        }
        if (orderNums.getWaitReceive() >= 0) {
            if (badge3 == null) {
                badge3 = new QBadgeView(mContext).bindTarget(menuOrder3).setBadgeNumber(orderNums.getWaitReceive());
                badge3.setShowShadow(false);
                badge3.setGravityOffset(16, true);
                badge3.setBadgeBackground(ContextCompat.getDrawable(mContext, R.color.colorPrimary), true);
                badge3.setBadgeTextSize(10, true);
            } else {
                badge3.setBadgeNumber(orderNums.getWaitReceive());
            }

        }
    }


    @OnClick({R.id.left_menu, R.id.right_menu, R.id.shop_menu2, R.id.shop_menu3, R.id.shop_menu4, R.id.shop_menu5, R.id.shop_menu6,
            R.id.shop_menu7, R.id.menu_order_1, R.id.menu_order_2, R.id.menu_order_3, R.id.menu_order_4, R.id.user_logo,
            R.id.order_no, R.id.sale_num, R.id.profit_num, R.id.fans_num, R.id.shop_manage,
            R.id.textView3, R.id.textView4, R.id.textView5, R.id.textView6, R.id.shop_menu1, R.id.shop_menu8,R.id.shop_menu9})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_menu:
                intent = new Intent(mContext, MessageListActivity.class);
                startActivity(intent);
                break;
            case R.id.right_menu:
               /*1我要开店2分享店铺3普通商品4限时购商品)-memberId(会员Id)-productId(商品Id)-limitId(限时购时间段Id)
                    这四个参数没有值的传0
                    例如普通商品分享：http://weixin.zj-yunti.com/authorizationPage.html?param=3-1-14-0*/
                String shareUrl = String.format("%1$s%2$d-%3$d-%4$d-%5$d", ApiClient.SHARE_URL, 2, memberId, 0, 0);
                ShareWindow shareWindow = new ShareWindow(mContext, shareUrl, member.getShopName(), member.getShopLogo(),
                        null, mContext.getResources().getString(R.string.share_shop_desc), null,null);
                shareWindow.showPopupWindow(rightMenu);
                break;
            case R.id.shop_menu1:
                //积分
                intent = new Intent(mContext, MyIntegralActivity.class);
                startActivity(intent);
                break;
            case R.id.shop_menu2:
                intent = new Intent(mContext, CustomerManageActivity.class);
                startActivity(intent);
                break;
            case R.id.shop_menu3:
                //业绩管理
                intent = new Intent(mContext, PerformanceActivity.class);
                startActivity(intent);
                break;
            case R.id.shop_menu4:
                intent = new Intent(mContext, SalesActivity.class);
                startActivity(intent);
                break;
            case R.id.shop_menu5:
                //客服
                intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra("url", ApiClient.CUSTOMER_URL);
                intent.putExtra("title", "客服");
                startActivity(intent);
                break;
            case R.id.shop_menu6:
                intent = new Intent(mContext, ShareGiftActivity.class);
                startActivity(intent);
                break;
            case R.id.shop_menu7:
                intent = new Intent(mContext, TeacherShareActivity.class);
                startActivity(intent);
                break;
            case R.id.shop_menu8:
                intent = new Intent(mContext, RefundOrderListActivity.class);
                intent.putExtra("type",1);
                startActivity(intent);
                break;
            case R.id.shop_menu9:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("type",2);
                startActivity(intent);
                break;
            case R.id.menu_order_1:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("page", 1);
                intent.putExtra("type",1);
                startActivity(intent);
                break;
            case R.id.menu_order_2:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("page", 2);
                intent.putExtra("type",1);
                startActivity(intent);
                break;
            case R.id.menu_order_3:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("page", 3);
                intent.putExtra("type",1);
                startActivity(intent);
                break;
            case R.id.menu_order_4:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("type",1);
                intent.putExtra("page", 0);
                startActivity(intent);
                break;
            case R.id.user_logo:
                intent = new Intent(mContext, ShopInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.textView3:
            case R.id.order_no:
                intent = new Intent(mContext, OrderListActivity.class);
                intent.putExtra("type",1);
                startActivity(intent);
                break;
            case R.id.textView4:
            case R.id.sale_num:
                intent = new Intent(mContext, SalesActivity.class);
                startActivity(intent);
                break;
            case R.id.textView5:
            case R.id.profit_num:
                intent = new Intent(mContext, TotalProfitActivity.class);
                startActivity(intent);
                break;
            case R.id.textView6:
            case R.id.fans_num:
                intent = new Intent(mContext, CustomerListActivity.class);
                startActivity(intent);
                break;
            case R.id.shop_manage:
                intent = new Intent(mContext, ShopManageActivity.class);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        member = BaseApp.getInstance().getMember();
        initView();
        getStatistics();
    }
}
